#include "TxtTerrainFileManager.h"
#include "../geom/TerrainModel.h"
#include <limits>
#include "VibModelFileManager.h"

#include <fstream>
#include <iostream>

using namespace dataengine;

bool TxtTerrainFileManager::canLoadFile() throw()
{
	return true;
}

geom::TerrainModel TxtTerrainFileManager::loadFile()
{
	geom::TerrainModel result;

	// Find max and min in every direction
	double maxDirs[3];
	double minDirs[3];
	maxDirs[0] = maxDirs[1] = maxDirs[2] = numeric_limits<double>::min();
	minDirs[0] = minDirs[1] = minDirs[2] = numeric_limits<double>::max();

	ifstream terrainFile(m_filename.c_str() , ifstream::in );

	while(terrainFile)
		for(int i=0;i<3;++i)
		{
			double number;
			terrainFile >> number;
			number/=10000.0;
			if(number < minDirs[i])
				minDirs[i] = number;
			if(number > maxDirs[i])
				maxDirs[i] = number;
		}

	double maxDist = 0;
	for(int i=0;i<3;i++)
		if(maxDirs[i] - minDirs[i] > maxDist)
			maxDist = maxDirs[i] - minDirs[i];

	terrainFile.clear();
	terrainFile.seekg(0,ios::beg);

	while(terrainFile)
	{
		util::Triplet<float> p;
		for(int i=0;i<3;++i)
		{
			float number;
			terrainFile >> number;
			number/=10000.0;
			p[i] = (number - (maxDirs[i] + minDirs[i])/2) * 100/ (maxDist);
		}
		result.addPoint(geom::Point3D(p[0],p[2],p[1]));
	}

	terrainFile.close();
    return result;
}

